<template>
    <div class="tableContainer">
        <el-form :inline="true" :model="formInline" class="demo-form-inline" @submit.native.prevent>
            <el-form-item label="">
                <el-input class="elInput" v-model="formInline.field" placeholder="输入角色名"></el-input>
            </el-form-item>
            
            <el-form-item>
                <el-button class="elBtn" type="primary" @click="selectRole">查询</el-button>
                <el-button class="elBtn" type="primary" @click="openDialog(1,'',1)">新增</el-button>
            </el-form-item>
        </el-form>
        <el-table :data="tableData" max-height="88%" border style="width: 100%">
            <el-table-column type="index" min-width="3%" align="center"></el-table-column>
            <el-table-column prop="name" label="角色名称"  min-width="10%" align="center"> </el-table-column>
            <el-table-column prop="description" label="描述"  min-width="40%" align="left"></el-table-column>
            <el-table-column prop="createUserId" label="创建人" min-width="10%" align="center"> </el-table-column>
            <el-table-column prop="createTime" label="创建时间" min-width="15%" align="center" :formatter="this.$common.dateFormat2"> </el-table-column>
            <el-table-column prop="status" label="状态" min-width="10%" align="center" :formatter="this.$common.statusFormat2"> </el-table-column>
            <el-table-column prop="op" label="操作" align="center" min-width="15%" >
                <template slot-scope="scope">
                    <el-button class="elBtn"  type="primary" size="mini" icon="edit"  @click="openDialog(scope.$index, scope.row,2)">修改</el-button>
                    <el-button size="mini" icon="delete" type="danger" 
                    @click="openDialog(scope.$index, scope.row,3)" 
                    v-if="scope.row.name !='管理员' && scope.row.name !='设计者' && scope.row.name!='专家团' && scope.row.name!='应用者'">删除</el-button>
                </template>
            </el-table-column>
        </el-table>
        <el-pagination background 
			layout="prev, pager, next, sizes, total, jumper"
			:page-sizes="pagesizes"
			:page-size="pagesize"
			:total="totalNum"
            @current-change="changePage"
            @size-change="sizeChange"
			>
		</el-pagination>

        <el-dialog :title="dialogTitle" :visible.sync="dialogFormVisible" width="50%" center @close="clearForm">
            <el-form :model="form" ref="form">
                <el-form-item label="角色名称" :label-width="formLabelWidth" prop="name" :rules="{validator:this.$common.emptyValidate, trigger: 'blur'}">
                    <el-input class="elInput" v-model="form.name" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="描述" :label-width="formLabelWidth" >
                    <el-input type="textarea" class="elInput" v-model="form.description" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="权限" :label-width="formLabelWidth" >
                    <el-transfer :data="authList" v-model="form.authId" :titles="['所有权限', '拥有权限']" ></el-transfer>
                </el-form-item>
                <el-form-item label="状态" :label-width="formLabelWidth">
                    <el-switch v-model="roleStatus" active-color="#13ce66" inactive-color="#ccc"  inactive-text="禁用" active-text="启用">
                    </el-switch>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="clearForm">取 消</el-button>
                <el-button class="elBtn" type="primary" @click="saveRole">确 定</el-button>
            </div>
        </el-dialog>

        <el-dialog title="提示" :visible.sync="centerDialogVisible" width="30%" center>
            <span>确定删除这条角色信息</span>
            <span slot="footer" class="dialog-footer">
                <el-button @click="centerDialogVisible = false">取 消</el-button>
                <el-button class="elBtn" type="primary" @click="doDeleteUser">确 定</el-button>
            </span>
        </el-dialog>
    </div>
    

</template>

<script>
export default {
    data() {
        return {
            dialogFormVisible:false, // 控制新增/修改对话框的显示隐藏
            centerDialogVisible:false, // 控制删除对话框的显示隐藏
            isAdd:true, // 新增修改标识
            roleId:"", // 选择的角色id
            dialogTitle:"新增角色", // 对话框标题
            pagesizes:[10,15,20,25],
            pagesize:10, // 每页条数
            currpage: 1, // 当前页
            totalNum:0, // 总数
            roleStatus:true,
            formLabelWidth: '20%', // label宽度
            tipMsg:"",
            formInline: { // 查询表单参数
                field: '',
            },
            form: { // 新增/修改表单参数
                name: '',
                description:"",
                createUserId:"",
                status:true,
                authId:[]
            },
            tableData: [], // 页面数据
            authList:[],
            // loading: true
      }
    },
    created(){
        // 获取屏幕高度
        this.clientHeight = this.$common.getClientHeight()
        this.pagesize = Math.ceil((this.clientHeight - 250)/55)
        this.pagesizes[0] = this.pagesize

        // 当页面初始化的时候，获取角色信息
        this.selectRole()
        this.selectAuth()
        this.form.createUserId = localStorage.userInfo?JSON.parse(localStorage.userInfo).userName:this.form.createUserId
    },
    methods:{
        // 打开对话框
        openDialog(index,row,type){
            if(type == 3){ // 删除
                this.centerDialogVisible = true
                this.roleId = row.id
            }else if(type == 2){ // 修改
                this.isAdd = false
                
                this.roleId = row.id
                this.selectRoleById()
                this.dialogTitle = "修改角色"
            }
            else if(type == 1){ // 新增
                this.isAdd = true
                this.dialogFormVisible = true
                this.dialogTitle = "新增角色"
            }
        },
        // 查询权限
        selectAuth(){
            this.$api.selectAuthAll().then(result=>{
                if(result.data.success){
                    this.authList = result.data.data
                    this.authList.forEach(element => {
                        element.key = element.id
                        element.label = element.name
                    });
                }
            })
        },
        // 查询角色数据
        selectRole(){
            const params = {
                key:this.formInline.field,
                page:this.currpage,
                limit:this.pagesize
            }
            this.$api.getRoleData({params:params})
            .then(result=>{
                var _this = this
                this.$common.filterLogin(result,_this,()=>{
                    if(result.data.success){
                        _this.tableData = result.data.data.rows
                        _this.totalNum = result.data.data.totalRows
                        // loading.close();
                    }
                })
                
            })
        },
        // 添加/修改角色
        saveRole(){
            this.$refs['form'].validate((valid) => {
                if(valid){
                    this.form.status = this.roleStatus?1:0
                    if(this.isAdd){ // 添加
                        this.$api.addRole(this.form).then(result=>{
                            this.successFun(result,1)
                        })
                    }else{ // 修改
                        this.$api.updateRole(this.form).then(result=>{
                            this.successFun(result,2)
                        })
                    }
                }
            })
        },
        // 根据id查询角色
        selectRoleById(id){
            this.$api.selectRoleById({params: {id: this.roleId}}).then(result=>{
                var _this = this
                this.$common.filterLogin(result,_this,()=>{
                    if(result.data.success){
                        // 获取权限值
                        result.data.data.authId = []
                        
                        result.data.data.authority.forEach(e => {
                            if(e && e!= null && e.id && e.id != null){
                                result.data.data.authId.push(e.id)
                            }
                        })

                        _this.form = result.data.data
                        _this.roleStatus = (_this.form.status == 1)?true:false
                        _this.dialogFormVisible = true
                    }
                })
                
            })
        },
        // 删除用户信息
        doDeleteUser(){
            this.$api.deleteRole({params: {id: this.roleId}}).then(result=>{
                this.successFun(result,3)
            })
        },
        successFun(result,type){
            var _this = this
            this.$common.filterLogin(result,_this,()=>{
                _this.clearForm(type)
                _this.tipMsg = result.data.message
                _this.selectRole()
                if(result.data.success){
                    _this.$message({center: true,message:"操作成功",type: 'success'});
                }else{
                    this.$message({center: true,message: result.data.message?result.data.message:"网络错误,请稍后再试",type: 'warning'});
                }
            })
        },
        // 清空表单
        clearForm(type){
            this.dialogFormVisible = false
            this.centerDialogVisible = false
            // this.$refs.form.resetFields()
            // 清楚表单数据
            for(let item in this.form){
                this.form[item] = ""
            }
            this.form.authId = []
            type != 3?this.$refs['form'].clearValidate():""
        },
        // 分页--改变当前页
        changePage(index){
            this.currpage = index
            this.selectRole()
        },
        // 分页--改变当前页显示条数
        sizeChange(page){
            this.pagesize = page
            this.selectRole()
        }
    },
}
</script>

<style lang="scss" scoped>
.tableContainer{
    height: 97%;
    padding: 10px;
    background: #FDFDFD;
    border-radius: 5px;
    .el-pagination.is-background{
        text-align: right;
        padding:10px 5px;
    }
    .el-table,.el-table th, .el-table tr{
        background: transparent !important;
    }
}
</style>